import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
import { CommonRedisService } from './service/common.redis.service';
import AppConfig from 'config/app.config';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly commonRedisService: CommonRedisService) {}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    if (AppConfig.AuthExternal.includes(request.path)) {
      return true
    }
    const token = request.headers['token']
    // 浙政钉小程序 飞控平台
    if (token === 'e44579a7c8df1a0d4ad5841978239e68') {
      return true
    }
    return this.commonRedisService.get(AppConfig.DingDing.AdminAccessTokenKey).then((res) => {
      return !!res && res === token;
    }).catch(() => {
      return false;
    })
  }
}
